﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel.DomainServices.Client.ApplicationServices;

namespace MyLiveMesh.ViewModels
{
    public class Login : Abstract
    {
        string m_username;
        string m_password;

        public string Username 
        {
            get
            {
                return (m_username);
            }

            set
            {
                if (m_username != value)
                {
                    m_username = value;
                    this.OnPropertyChanged("Username");
                }
            }
        }
        public string Password
        {
            get
            {
                return (m_password);
            }

            set
            {
                if (m_password != value)
                {
                    m_password = value;
                    this.OnPropertyChanged("Password");
                }
            }
        }
        public ICommand LoginCommand
        {
            get
            {
                return (new CommandLogin(this));
            }
        }

        public Login()
        {
        }
    }

    public class CommandLogin : ICommand
    {
        Login m_login;
        ChildWindow m_window;

        public CommandLogin(Login _login)
        {
            m_login = _login;
        }

        #region ICommand Membres

        public bool CanExecute(object parameter)
        {
            return (!WebContext.Current.Authentication.IsLoggingIn && parameter is ChildWindow);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            m_window = parameter as ChildWindow;
            WebContext.Current.Authentication.Login(new LoginParameters(m_login.Username, m_login.Password), LoginOperation_Completed, null);
        }

        #endregion

        private void LoginOperation_Completed(LoginOperation loginOperation)
        {
            if (loginOperation.LoginSuccess)
            {
                m_window.Close();
            }
            else if (loginOperation.HasError)
            {
                MessageBox.Show(loginOperation.Error.Message);
                loginOperation.MarkErrorAsHandled();
            }
            else if (!loginOperation.IsCanceled)
            {
                MessageBox.Show("Error: Bad username or password");
                //this.loginInfo.ValidationErrors.Add(new ValidationResult(ErrorResources.ErrorBadUserNameOrPassword, new string[] { "UserName", "Password" }));
            }
        }
    }
}
